import { memo, useMemo } from 'react'
import { styled } from '@umijs/max'
import { MenuAll, getMenu } from '@/services/common'
import { useRequest } from 'ahooks'
import { cleanMenuDataForOption } from '@/utils/getMenuInfo'
import { Tree } from 'antd'

const Container = styled.div`
  width: 100%;
`

export interface MenuTreeProps {
  value?: string[]
  onChange?: (value: string[]) => void
  all?: MenuAll
  disabled?: boolean
}

type Option = {
  key: string
  children: Option[]
}
const getChildKeys = (value: Option[]) => {
  const result: string[] = []
  const loop = (value: Option[]) => {
    value.forEach(item => {
      result.push(item.key)
      if (item.children?.length) {
        loop(item.children)
      }
    })
  }
  loop(value)
  return result
}

const MenuTree: React.FC<MenuTreeProps> = props => {
  const { data: menuList } = useRequest(() => getMenu({all: props.all}))

  const menuTree = useMemo(() => {
    return cleanMenuDataForOption(menuList?.data || [])
  }, [menuList])

  const onCheck = ({checked: checkedKeys}: any, {checked, node}: any) => {
    if (node.children?.length) {
      const childrenKeys = getChildKeys(node.children)
      if (checked) {
        props.onChange?.(Array.from(new Set([...checkedKeys, ...childrenKeys])))
      } else {
        props.onChange?.(checkedKeys.filter((it: string) => !childrenKeys.some((_it: string) => it === _it)))
      }
    } else if (node.parentId && checked && !checkedKeys.some((it: string) => it === node.parentId)) {
      props.onChange?.([...checkedKeys, node.parentId])
    } else {
      props.onChange?.(checkedKeys)
    }
  }
  
  return (
    <Container>
      <Tree
        checkable
        autoExpandParent
        onCheck={onCheck as any}
        checkedKeys={props.value}
        treeData={menuTree}
        checkStrictly
        disabled={props.disabled}
      />
    </Container>
  )
}

export default memo(MenuTree)